{% extends "layout.html" %}
{% set active_page = "live" %}
{% set help_page = ["https://kizniche.github.io/Mycodo/Data-Viewing/#live-measurements", _('Live Measurements')] %}

{% block title %} - {{_('Live Measurements')}}{% endblock %}

{% block head %}
  <script>
    function updateMeasurements(unique_id, measure_type, measurement_id, period) {
      const url = '/last/' + unique_id + '/' + measure_type + '/' + measurement_id + '/' + period.toString();
      let measure_string = '';
      measure_string = unique_id + '-' + measure_type + '-' + measurement_id;
      $.ajax(url, {
        success: function(data, responseText, jqXHR) {
          if (jqXHR.status === 204) {
            if (period === 0) document.getElementById(measure_string + "-time").innerHTML = "No Data Found";
            else document.getElementById(measure_string + "-time").innerHTML = "No Data Last " + period.toString() + " sec";
            document.getElementById(measure_string + "-value").innerHTML = "0";
          }
          else {
            const time = data[0] * 1000;
            const measurement_val = parseFloat(data[1].toFixed(3)).toString();
            const date = new Date(parseFloat(time));
            const year = date.getFullYear();
            const month = date.getMonth() + 1;
            const day = date.getDate();
            const hours = date.getHours();
            const minutes = "0" + date.getMinutes();
            const seconds = "0" + date.getSeconds();
            document.getElementById(measure_string + "-time").innerHTML = year + "/" + month + "/" + day + " " + hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
            document.getElementById(measure_string + "-value").innerHTML = measurement_val;
          }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          if (period === 0) document.getElementById(measure_string + "-time").innerHTML = "Error: No Data Found";
          else document.getElementById(measure_string + "-time").innerHTML = "Error: No Data Last " + period.toString() + " sec";
          document.getElementById(measure_string + "-value").innerHTML = "0";
        },
        cache: false
      });
    }

    function liveTextData(unique_id, measure_type, measurement_id, period, refresh) {
      updateMeasurements(unique_id, measure_type, measurement_id, period);
      setInterval(function () {
        updateMeasurements(unique_id, measure_type, measurement_id, period);
      }, refresh * 1000);
    }

    $(function() {
      {%- for each_input in table_input.query.filter(table_input.is_activated).all() -%}
        {% for each_meas in table_device_measurements.query.filter(table_device_measurements.device_id == each_input.unique_id).all() if each_meas.is_enabled %}
          {%- if each_input.device in dict_inputs and 'listener' in dict_inputs[each_input.device] and dict_inputs[each_input.device]['listener'] %}
            {%- set period = 0 %}
            {%- set period_refresh = 30 %}
          {%-  else %}
            {%- set period = each_input.period * 2 %}
            {%- set period_refresh = each_input.period %}
          {%- endif %}
          liveTextData('{{each_input.unique_id}}', 'input', '{{each_meas.unique_id}}', {{period}}, {{period_refresh}});
        {% endfor %}
      {%- endfor -%}

      {%- for each_function in table_function.query.filter(table_function.is_activated).all() -%}
        {% for each_meas in table_device_measurements.query.filter(table_device_measurements.device_id == each_function.unique_id).all() if each_meas.is_enabled %}
          {%  set function_options = custom_options_values_controllers[each_function.unique_id] %}
          {% if "period" in function_options %}
            {% set function_period = function_options["period"] %}
          {% endif %}
          {% if function_period %}
          liveTextData('{{each_function.unique_id}}', 'function', '{{each_meas.unique_id}}', {{function_period * 2}}, {{function_period}});
          {% else %}
          liveTextData('{{each_function.unique_id}}', 'function', '{{each_meas.unique_id}}', 0, 30);
          {% endif %}
        {% endfor %}
      {%- endfor -%}
    });
  </script>
{% endblock %}

{%- block body %}
  <!-- Route: /live -->
  <main role="main" class="container">

    {% include 'flash_messages.html' %}

    {%- if not activated_inputs and not activated_functions -%}
    <div>
      {{_('No Inputs/Functions Activated')}}. <a href="/input">Click here</a> to go to the Input page. Read the <a href="https://kizniche.github.io/Mycodo">Manual</a> to become more familiar with the system and configuration options.
    </div>
    {%- endif -%}

    {% for each_input in table_input.query.filter(table_input.is_activated.is_(True)).order_by(table_input.position_y.asc()).all() %}

    <div style="padding: 0.5em; margin-bottom: 0.7em; border: 1px solid #ddd; border-radius: 5px;">

      <div class="row">
        <div class="col-12 col-sm-6 text-left">
          {{each_input.name}} (Input {{each_input.unique_id[:8]}})
      {%- if each_input.device != 'EDGE' -%}
            <div>
               {{_('Input (%(type)s), %(sec)s second interval', type=each_input.device, sec=each_input.period)}}
            </div>
      {%- endif -%}
        </div>

        <div class="col-12 col-sm-6 text-right">
          {{_('Measurement')}} | {{_('Timestamp')}}
      {% for each_meas in table_device_measurements.query.filter(table_device_measurements.device_id == each_input.unique_id).all() if each_meas.is_enabled %}
        {% set measure_string = each_input.unique_id + '-input-' + each_meas.unique_id %}
          <div>
            <b><span id="{{measure_string}}-value">0.0</span>

        {%- if dict_units[dict_measure_units[each_meas.unique_id]]['unit'] -%}
            {{' ' + dict_units[dict_measure_units[each_meas.unique_id]]['unit']}}
        {%- endif -%}</b>

        {%- if each_meas.conversion_id or each_meas.rescaled_unit -%}
            {{' (' + dict_units[dict_measure_units[each_meas.unique_id]]['name'] + ') '}}
        {%- else -%}
            {{' (' + dict_measurements[each_meas.measurement]['name'] + ') '}}
        {%- endif -%}

        {%- if each_meas.name -%}
            {{' (' + each_meas.name + ') '}}
        {%- endif -%}

            CH{{each_meas.channel}} | <span id="{{measure_string}}-time">&lt;{{_('Please wait')}}&gt;</span><br>
          </div>
      {% endfor %}
        </div>
      </div>

    </div>

    {%- endfor -%}

    {% for each_function in table_function.query.filter(table_function.is_activated.is_(True)).order_by(table_function.position_y.asc()).all() %}
      {%- set func_measurements = table_device_measurements.query.filter(
                                      table_device_measurements.device_id == each_function.unique_id).all() -%}

      {%- if func_measurements -%}
        {%  set function_options = custom_options_values_controllers[each_function.unique_id] %}
        {% if "period" in function_options %}
          {% set function_period = function_options["period"] %}
        {% endif %}

    <div style="padding: 0.5em; margin-bottom: 0.7em; border: 1px solid #ddd; border-radius: 5px;">

      <div class="row">
        <div class="col-12 col-sm-6 text-left">
          {{each_function.name}} (Function {{each_function.unique_id[:8]}})
          <div>
        {% if function_period %}
            {{_('Function (%(type)s), %(sec)s second interval', type=each_function.device, sec=function_period)}}
        {% else %}
            {{_('Function (%(type)s)', type=each_function.function_type)}}
        {% endif %}
          </div>
        </div>

        <div class="col-12 col-sm-6 text-right">
          {{_('Measurement')}} | {{_('Timestamp')}}
        {% for each_meas in func_measurements if each_meas.is_enabled %}
          {% set measure_string = each_function.unique_id + '-function-' + each_meas.unique_id %}
          <div>
            <b><span id="{{measure_string}}-value">0.0</span>

          {%- if dict_measure_units[each_meas.unique_id] in dict_units and dict_units[dict_measure_units[each_meas.unique_id]]['unit'] -%}
            {{' ' + dict_units[dict_measure_units[each_meas.unique_id]]['unit']}}
          {%- endif -%}</b>

          {%- if dict_measure_measurements[each_meas.unique_id] in dict_measurements and dict_measurements[dict_measure_measurements[each_meas.unique_id]]['name'] -%}
            {{' (' + dict_measurements[dict_measure_measurements[each_meas.unique_id]]['name'] + ') '}}
          {%- elif dict_measure_units[each_meas.unique_id] in dict_units and dict_units[dict_measure_units[each_meas.unique_id]]['name'] -%}
            {{' (' + dict_units[dict_measure_units[each_meas.unique_id]]['name'] + ') '}}
          {%- endif -%}

          {%- if each_meas.name -%}
            {{' (' + each_meas.name + ') '}}
          {%- endif -%}

            CH{{each_meas.channel}} | <span id="{{measure_string}}-time">&lt;{{_('Please wait')}}&gt;</span><br>
          </div>
        {% endfor %}
        </div>

      </div>

    </div>

      {% endif %}
    {%- endfor -%}

  </main>

{% endblock -%}
